﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using EmitMapper;
using InnovaApp.Layers.DataLayer;
using InnovaApp.Layers.ResourcesLayer.Properties;
using InnovaApp.Layers.SecurityLayer.Models;
using InnovaApp.Layers.SecurityLayer.Models.AccountModels.MembershipServices;
using InnovaApp.Layers.SecurityLayer.Models.MetaModels;
using INNOVACALL.Framework.Common;
using INNOVACALL.Framework.Common.CodeFormatting;
using INNOVACALL.Framework.Common.Models;

namespace InnovaApp.Layers.SecurityLayer.Controllers
{
	public class LogOnController : _Controllers_Base<LogOnModel>
	{
		public IFormsAuthenticationService FormsService { get; set; }
		public IMembershipService MembershipService { get; set; }

		protected override void Initialize(RequestContext requestContext)
		{
			base.eMethodBase = "InnovaApp.Layers.SecurityLayer.Controllers.LogOnController";
			base.specificCssCollection = new string[] { "_FormCommon.css", "Views/Account/AccountCommon.css", "ClientComponents/CodeFormatting/csharp.css", "ClientComponents/KendoUI/kendo.common.min.css", "ClientComponents/KendoUI/kendo.blueopal.min.css" };
			base.specificJSCollection = null;
			base.dynamicJSCollection = new string[] { "/ScriptsG/inoLogOnDynamic.js" };
			base.specificJqueryJSCollection = new string[] { "InnovacallJS/LogOn/LogOn.js" };
			base.jsVariables = null;
			base.externalCSS = null;
			base.Meta.Add(enMeta.Description, Resources.View_LogOn_Meta_Description);
			base.Meta.Add(enMeta.Keywords, Resources.View_LogOn_Meta_Keywords);
			base.Meta.Add(enMeta.Subject, Resources.View_LogOn_Meta_Subject);

			if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
			if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
			base.Initialize(requestContext);
		}

		#region LogOn

		/// <summary>
		/// URL: /Account/LogOn
		/// </summary>
		/// <returns></returns>
		public ActionResult Index()
		{
			using (DataRepositories _dataContext = new DataRepositories())
			{
				base.InitView(
					Resources.View_Register_PageTitle,
					string.Empty,
					specificCssCollection,
					specificJSCollection,
					dynamicJSCollection,
					specificJqueryJSCollection,
					jsVariables,
					externalCSS,
					Meta,
					_dataContext,
					false
					);
			}
            string returnUrl = Request.QueryString["ReturnUrl"];
            if (!string.IsNullOrEmpty(returnUrl))
            {
                ContentData.ReturnUrl = returnUrl;
            }
			return View(ContentData);
		}


		[HttpPost]
		public ActionResult Index(LogOnModel model)
		{
			if (ModelState.IsValid)
			{
				using (DataRepositories _dataContext = new DataRepositories())
				{
					if (MembershipService.ValidateUser(model.Credentials.UserName, model.Credentials.Password))
					{
						FormsService.SignIn(model.Credentials.UserName, model.Credentials.RememberMe);

                        if (Url.IsLocalUrl(model.ReturnUrl))
						{
                            return Redirect(model.ReturnUrl);
						}
						else
						{
							return RedirectToAction("Index", "Home");
						}
					}
					else
					{
						ModelState.AddModelError("", Resources.View_Account_LogOn_NameOrPasswordWasIncorrect);
					}
					//In this case, we return to the same page, we need to re initialize view.
					base.InitilializationView(
						Resources.View_LogOn_PageTitle,
						Resources.View_LogOn_PageMessage,
						specificCssCollection,
						specificJSCollection,
						dynamicJSCollection,
						specificJqueryJSCollection,
						jsVariables,
						externalCSS,
						false,
						Meta
						);

					ContentData.InvolvedCode = new InvolvedCodeModel();
					ContentData.InvolvedCode.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Html, TabStripName = "View", TabStripContent = "/Views/LogOn/Index.cshtml" });
					ContentData.InvolvedCode.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Html, TabStripName = "Layout", TabStripContent = "/Views/Shared/_Layout.cshtml" });
					ContentData.InvolvedCode.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.cSharp, TabStripName = "Controller", TabStripContent = "/../Layers/SecurityLayer/Controllers/LogOnController.cs" });
					ContentData.InvolvedCode.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.cSharp, TabStripName = "Model", TabStripContent = "/Models/LogOn.cs" });
					ContentData.InvolvedCode.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Javascript, TabStripName = "View JS", TabStripContent = "/Scripts/InnovacallJS/LogOn/LogOn.js" });
					ContentData.InvolvedCode.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Javascript, TabStripName = "Layout JS", TabStripContent = "/Scripts/InnovacallJS/_Layout/_Layout.js" });
					ContentData.InvolvedCode.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Html, TabStripName = "Script G View", TabStripContent = "/Views/ScriptsG/inoLogOnDynamic.cshtml" });
					ContentData.InvolvedCode.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.GeneratedJavascript, TabStripName = "View Generated JS", TabStripContent = "/ScriptsG/inoLogOnDynamic.js" });
					RenderCodeFiles(ContentData.InvolvedCode);
					
					ContentData.Credentials = ObjectMapperManager.DefaultInstance.GetMapper<LogOn_MetaModel,LogOn_MetaModel>().Map(model.Credentials);
				}
			}
			return View(ContentData);
		}

		#endregion

		#region LogOff

		/// <summary>
		/// URL: /Account/LogOff
		/// </summary>
		/// <returns></returns>
		public ActionResult LogOff()
		{
			FormsService.SignOut();
			Session.Abandon();
			return RedirectPermanent("~/");
		}

		#endregion
	}
}
